/**
 * 
 */
package org.t2.backstage.module.giftcode;

import org.banish.sql.core.util.QuerySet;
import org.gaming.backstage.PageData;
import org.gaming.backstage.interceptor.RoleContext;
import org.gaming.backstage.module.user.service.UserService;
import org.gaming.service.advice.ResponseResult;
import org.gaming.service.apidoc.annotation.ApiDocument;
import org.gaming.service.asserts.Asserts;
import org.gaming.tool.DateTimeUtil;
import org.gaming.tool.GsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.t2.backstage.module.TipsCode;
import org.t2.backstage.module.gameserver.model.GameChannel;
import org.t2.backstage.module.gameserver.model.GameServer;
import org.t2.backstage.module.gameserver.service.GameChannelService;
import org.t2.backstage.module.gameserver.service.GameServerService;
import org.t2.backstage.module.giftcode.form.GiftCodeForm;
import org.t2.backstage.module.giftcode.model.GiftCode;
import org.t2.backstage.module.giftcode.model.GiftCodeRandomLog;
import org.t2.backstage.module.giftcode.model.GiftCodeShareLog;
import org.t2.backstage.module.giftcode.service.GiftCodeRandomLogService;
import org.t2.backstage.module.giftcode.service.GiftCodeService;
import org.t2.backstage.module.giftcode.service.GiftCodeShareLogService;
import org.t2.backstage.module.giftcode.struct.GiftCodeQuery;
import org.t2.backstage.module.giftcode.vo.GiftCodeVo;
import org.t2.backstage.module.player.model.Player;
import org.t2.backstage.module.player.service.PlayerService;
import org.t2.backstage.util.T2HttpUtil;

import sh.t2.share.apiutil.GameApi;
import sh.t2.share.module.giftcode.GiftCodeApiProtocol.GiftCodeRequest;
import sh.t2.share.module.giftcode.GiftCodeApiProtocol.GiftCodeResponse;
import sh.t2.share.module.mail.MailAttachment;
import sh.t2.share.module.server.form.ServerApiProtocol.ServerCheckRewardsRequest;
import sh.t2.share.module.server.form.ServerApiProtocol.ServerCheckRewardsResponse;

/**
 * @author YY
 *
 */
@Controller
public class GiftCodeController {

	@Autowired
	private GiftCodeService giftCodeService;
	@Autowired
	private UserService userService;
	@Autowired
	private GiftCodeShareLogService giftCodeShareLogService;
	@Autowired
	private GiftCodeRandomLogService giftCodeRandomLogService;
	@Autowired
	private PlayerService playerService;
	@Autowired
	private GameServerService gameServerService;
	@Autowired
	private GameChannelService gameChannelService;

	@ApiDocument("请求礼包码数据")
	@RequestMapping(value = "/giftCode/data.auth")
	@ResponseBody
	public PageData<GiftCodeVo> data(GiftCodeQuery query) {
		QuerySet querySet = new QuerySet();
		if (query.getCode() != null && !"".equals(query.getCode())) {
			querySet.addCondition("code like ?", "%" + query.getCode() + "%");
		}
		if (query.getName() != null && !"".equals(query.getName())) {
			querySet.addCondition("name like ?", "%" + query.getName() + "%");
		}
		querySet.limit(query.getPage(), query.getLimit());
		querySet.orderBy("order by id desc");
		querySet.formWhere();
		
		PageData<GiftCode> datas = giftCodeService.query(querySet);
		
		PageData<GiftCodeVo> pageData = new PageData<>();
		pageData.setCount(datas.getCount());
		for(GiftCode giftCode : datas.getData()) {
			GiftCodeVo vo = new GiftCodeVo();
			vo.setId(giftCode.getId());
			vo.setName(giftCode.getName());
			vo.setCode(giftCode.getCode());
			vo.setType(giftCode.getType());
			vo.setRewards(giftCode.getRewards());
			vo.setNum(giftCode.getNum());
			if(giftCode.getChannelId() <= 0) {
				vo.setChannel("全渠道");
			} else {
				GameChannel gameChannel = gameChannelService.getEntity(0, giftCode.getChannelId());
				if(gameChannel == null) {
					vo.setChannel("异常");
				} else {
					vo.setChannel(gameChannel.getName() + "[" + gameChannel.getId() + "]");
				}
			}
			if(giftCode.getServerUid() <= 0) {
				vo.setServer("全服务器");
			} else {
				GameServer gameServer = gameServerService.getEntity(0, giftCode.getServerUid());
				if(gameServer == null) {
					vo.setServer("异常");
				} else {
					vo.setServer(gameServer.getName() + "[" + gameServer.getId() + "]");
				}
			}
			vo.setExpireTime(giftCode.getExpireTime());
			vo.setUsable(giftCode.isUsable());
			vo.setUserId(giftCode.getUserId());
			vo.setUserName(giftCode.getUserName());
			vo.setUseUserId(giftCode.getUseUserId());
			vo.setUseUserName(giftCode.getUseUserName());
			vo.setChannelId(giftCode.getChannelId());
			vo.setServerUid(giftCode.getServerUid());
			pageData.getData().add(vo);
		}
		return pageData;
	}

	@ApiDocument("新增礼包码数据")
	@RequestMapping(value = "/giftCode/save.authw")
	@ResponseBody
	public void save(GiftCodeForm form) {
		RoleContext roleContext = userService.getCurrUser();

		//验证奖励是否合法
		GameServer gameServer = gameServerService.randomRunning();
		
		ServerCheckRewardsRequest request = new ServerCheckRewardsRequest();
		request.rewards = GsonUtil.getList(form.getRewards(), MailAttachment.class);
		ResponseResult<ServerCheckRewardsResponse> responseResult = T2HttpUtil.jsonPost(gameServer,
				GameApi.serverCheckRewards, request, ServerCheckRewardsResponse.class);
		Asserts.isTrue(responseResult != null, TipsCode.GIFTCODE_REWARD_ERROR);
		ServerCheckRewardsResponse response = responseResult.getData();
		
		GiftCode giftCode = null;
		if (form.getId() > 0) {
			giftCode = giftCodeService.getEntity(form.getId());
			Asserts.isTrue(giftCode != null, TipsCode.GIFTCODE_NOT_EXIST);
			Asserts.isTrue(!giftCode.isUsable(), TipsCode.GIFTCODE_USING);

			if (form.getType() == 2) {
				giftCode.setNum(form.getNum());
			}
			giftCode.setName(form.getName());
			giftCode.setExpireTime(form.getExpireTime());

			giftCode.setRewards(response.rewards);
			giftCode.setChannelId(form.getChannelId());
			giftCode.setServerUid(form.getServerUid());

			giftCodeService.update(giftCode);
		} else {
			giftCode = new GiftCode();
			if (form.getType() == 1) {
				QuerySet querySet = new QuerySet();
				querySet.addCondition("code = ?", form.getCode());
				querySet.formWhere();
				PageData<GiftCode> pageData = giftCodeService.query(querySet);
				Asserts.isTrue(pageData.getCount() <= 0, TipsCode.GIFTCODE_EXIST);
				
				giftCode.setType(1);
				giftCode.setCode(form.getCode());
				giftCode.setNum(1);
			} else {
				giftCode.setType(2);
				giftCode.setCode("随机生成");
				giftCode.setNum(form.getNum());
			}
			giftCode.setUserId(roleContext.getId());
			giftCode.setUserName(roleContext.getName());

			giftCode.setName(form.getName());
			giftCode.setExpireTime(form.getExpireTime());

			giftCode.setRewards(response.rewards);
			giftCode.setChannelId(form.getChannelId());
			giftCode.setServerUid(form.getServerUid());

			giftCodeService.insert(giftCode);
		}
	}

	@ApiDocument("启用礼包码")
	@RequestMapping(value = "/giftCode/usable.authw")
	@ResponseBody
	public void markUsable(@RequestParam("id") long id) {
		GiftCode giftCode = giftCodeService.getEntity(id);
		Asserts.isTrue(giftCode != null, TipsCode.GIFTCODE_NOT_EXIST);
		Asserts.isTrue(!giftCode.isUsable(), TipsCode.GIFTCODE_USING);
		
		RoleContext roleContext = userService.getCurrUser();
		
		giftCode.setUsable(true);
		giftCode.setUseUserId(roleContext.getId());
		giftCode.setUseUserName(roleContext.getName());
		giftCodeService.update(giftCode);
		
		if(giftCode.getType() == 2) {
			giftCodeRandomLogService.trySpawnCodes(giftCode, 8);
		}
	}
	
	@ApiDocument("礼包码是否可用，给游戏服的接口")
	@RequestMapping(value = GameApi.useGiftCode)
	@ResponseBody
	public GiftCodeResponse useGiftCode(@RequestBody GiftCodeRequest request) {
		Player player = playerService.getEntity(request.playerId);
		
		QuerySet querySet = new QuerySet();
		querySet.addCondition("code = ?", request.code.toLowerCase());
		querySet.formWhere();
		PageData<GiftCode> giftCodes = giftCodeService.query(querySet);
		if (giftCodes.getData().isEmpty()) {
			PageData<GiftCodeRandomLog> randomCodes = giftCodeRandomLogService.query(querySet);
			if(randomCodes.getData().isEmpty()) {
				// 兑换码无效
				GiftCodeResponse response = new GiftCodeResponse();
				response.tipsCode = 1;
				return response;
			} else {
				// 随机码
				GiftCodeRandomLog randomCode = randomCodes.getData().get(0);
				if(randomCode.getPlayerId() > 0) {
					//已经被使用
					GiftCodeResponse response = new GiftCodeResponse();
					response.tipsCode = 2;
					return response;
				}
				GiftCode giftCode = giftCodeService.getEntity(randomCode.getGiftId());
				if(DateTimeUtil.currMillis() > giftCode.getExpireTime()) {
					GiftCodeResponse response = new GiftCodeResponse();
					response.tipsCode = 1;
					return response;
				}
				if(giftCode.getChannelId() > 0 && player.getChannelId() != giftCode.getChannelId()) {
					GiftCodeResponse response = new GiftCodeResponse();
					response.tipsCode = 1;
					return response;
				}
				if(giftCode.getServerUid() > 0) {
					GameServer gameServer = gameServerService.getEntity(0, giftCode.getServerUid());
					if(player.getServerId() != gameServer.getServerId()) {
						GiftCodeResponse response = new GiftCodeResponse();
						response.tipsCode = 1;
						return response;
					}
				}
				
				QuerySet queryUsed = new QuerySet();
				queryUsed.addCondition("gift_id = ?", giftCode.getId());
				queryUsed.addCondition("player_id = ?", player.getId());
				queryUsed.formWhere();
				PageData<GiftCodeRandomLog> usedCodes = giftCodeRandomLogService.query(queryUsed);
				if(!usedCodes.getData().isEmpty()) {
					//已经使用过同类
					GiftCodeResponse response = new GiftCodeResponse();
					response.tipsCode = 3;
					return response;
				}
				randomCode.setPlayerId(player.getId());
				randomCode.setPlayerName(player.getNick());
				randomCode.setUseTime(DateTimeUtil.currMillis());
				GameServer gameServer = gameServerService.getByPlatformAndServer(player.getPlatformId(), player.getServerId());
				if(gameServer != null) {
					randomCode.setServerId(gameServer.getServerId());
					randomCode.setServerName(gameServer.getName());
				}
				giftCodeRandomLogService.update(randomCode);
				
				GiftCodeResponse response = new GiftCodeResponse();
				response.rewards = GsonUtil.toJson(giftCode.getRewards());
				return response;
			}
		} else {
			// 通码
			GiftCode giftCode = giftCodes.getData().get(0);
			if(giftCode.getType() != 1) {
				GiftCodeResponse response = new GiftCodeResponse();
				response.tipsCode = 1;
				return response;
			}
			if(!giftCode.isUsable()) {
				GiftCodeResponse response = new GiftCodeResponse();
				response.tipsCode = 1;
				return response;
			}
			if(DateTimeUtil.currMillis() > giftCode.getExpireTime()) {
				GiftCodeResponse response = new GiftCodeResponse();
				response.tipsCode = 1;
				return response;
			}
			if(giftCode.getChannelId() > 0 && player.getChannelId() != giftCode.getChannelId()) {
				GiftCodeResponse response = new GiftCodeResponse();
				response.tipsCode = 1;
				return response;
			}
			if(giftCode.getServerUid() > 0) {
				GameServer gameServer = gameServerService.getEntity(0, giftCode.getServerUid());
				if(player.getServerId() != gameServer.getServerId()) {
					GiftCodeResponse response = new GiftCodeResponse();
					response.tipsCode = 1;
					return response;
				}
			}
			QuerySet queryUsed = new QuerySet();
			queryUsed.addCondition("gift_id = ?", giftCode.getId());
			queryUsed.addCondition("player_id = ?", player.getId());
			queryUsed.formWhere();
			PageData<GiftCodeShareLog> usedCodes = giftCodeShareLogService.query(queryUsed);
			if(!usedCodes.getData().isEmpty()) {
				//已经使用过同类
				GiftCodeResponse response = new GiftCodeResponse();
				response.tipsCode = 3;
				return response;
			}
			GiftCodeShareLog shareLog = new GiftCodeShareLog();
			shareLog.setGiftId(giftCode.getId());
			shareLog.setCode(giftCode.getCode());
			shareLog.setPlayerId(player.getId());
			shareLog.setPlayerName(player.getNick());
			GameServer gameServer = gameServerService.getByPlatformAndServer(player.getPlatformId(), player.getServerId());
			if(gameServer != null) {
				shareLog.setServerId(gameServer.getServerId());
				shareLog.setServerName(gameServer.getName());
			}
			giftCodeShareLogService.insert(shareLog);
			
			GiftCodeResponse response = new GiftCodeResponse();
			response.rewards = GsonUtil.toJson(giftCode.getRewards());
			return response;
		}
	}
}
